package com.ba.baseandroid


import HttpConfig
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.OnLifecycleEvent
import com.alibaba.android.arouter.launcher.ARouter
import com.ba.base.UrlType
import com.example.jcenterlibrary.BuildConfig
import com.ba.base.utils.LoginResultHelper
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.onAdaptListener
import me.jessyan.autosize.utils.AutoSizeLog
import qsos.core.exception.GlobalException
import qsos.core.exception.GlobalExceptionHelper
import java.util.*
import qsos.core.lib.config.CoreConfig
import qsos.lib.base.base.BaseApplication
import qsos.lib.base.utils.LogUtil
import qsos.lib.base.utils.rx.RxBus
import qsos.lib.netservice.ApiEngine
import timber.log.Timber

/**
 * AppApplication
 */
open class App(
    override var debugARouter: Boolean = false,
    override var debugTimber: Boolean = true
) : BaseApplication(), LifecycleOwner {

    companion object {
        private lateinit var instance: App
        var appContext: Context? = null
        fun myApplication(): App {
            return instance
        }
    }

    init {
        /**BASE配置*/
        CoreConfig.DEBUG = BuildConfig.DEBUG

        // 设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            layout.setPrimaryColorsId(R.color.white, R.color.black)
            ClassicsHeader(context)
        }
        // 设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout ->
            layout.setPrimaryColorsId(R.color.white, R.color.black)
            ClassicsFooter(context)
        }

        AutoSizeConfig.getInstance().apply {
//            unitsManager.isSupportDP = false
//            unitsManager.supportSubunits = Subunits.MM
        }.onAdaptListener = object : onAdaptListener {
            override fun onAdaptBefore(target: Any?, activity: Activity?) {
                //使用以下代码, 可以解决横竖屏切换时的屏幕适配问题
                //使用以下代码, 可支持 Android 的分屏或缩放模式, 但前提是在分屏或缩放模式下当用户改变您 App 的窗口大小时
                //系统会重绘当前的页面, 经测试在某些机型, 某些情况下系统不会主动重绘当前页面, 所以这时您需要自行重绘当前页面
//                ScreenUtils.getScreenSize(activity) //参数一定要不要传 Application!!!
//                AutoSizeConfig.getInstance().setScreenWidth(ScreenUtils.getScreenSize(activity)[0])
//                 AutoSizeConfig.getInstance().setScreenHeight(ScreenUtils.getScreenSize(activity)[1])
                AutoSizeLog.d(
                    String.format(
                        Locale.ENGLISH,
                        "%s onAdaptBefore!",
                        target?.javaClass?.name
                    )
                )

            }

            override fun onAdaptAfter(target: Any?, activity: Activity?) {
                AutoSizeLog.d(
                    String.format(
                        Locale.ENGLISH,
                        "%s onAdaptAfter!",
                        target?.javaClass?.name
                    )
                )
            }
        }

    }

    override fun getLifecycle(): Lifecycle {
        return LifecycleRegistry(this)
    }

    @SuppressLint("CheckResult", "BinaryOperationInTimber")
    override fun onCreate() {
        super.onCreate()
        appContext = this
        instance = this
        /**Timber 日志*/
        LogUtil.open(true, GlobalExceptionHelper.CrashReportingTree())
        /**全局异常捕获处理*/
        Thread.setDefaultUncaughtExceptionHandler(GlobalExceptionHelper)
        RxBus.toFlow(GlobalExceptionHelper.ExceptionEvent::class.java).subscribe {
            dealGlobalException(it.exception)
        }

        if (CoreConfig.DEBUG) {
//            CoreConfig.BASE_URL = SharedPreUtils.getBaseUrl(this)
            CoreConfig.BASE_URL = UrlType.DEV.url
        } else {
            CoreConfig.BASE_URL = UrlType.RELEASE.url
        }
        CoreConfig.PROVIDER = "com.screx.mcloud.provider"
        Timber.tag("环境配置").d(
            "\nDEBUG=${CoreConfig.DEBUG}" +
                    "\nBASE_URL=${CoreConfig.BASE_URL}" +
                    "\nPROVIDER=${CoreConfig.PROVIDER}"
        )
        // 网络请求配置
        ApiEngine.init(HttpConfig())

        var cb = object : QbSdk.PreInitCallback {
            override fun onViewInitFinished(arg0: Boolean) {
                // TODO Auto-generated method stub
                //初始化完成回调
            }

            override fun onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        }
        //腾讯x5webview初始化
        QbSdk.initX5Environment(applicationContext, cb)

        //是否进行ARouter调试(可以通过AppConfig.isDebug=true/false来判断日志的是否开启)
        if (CoreConfig.DEBUG) {
            //下面两句话必须放到init前面,否则配置无效
            ARouter.openLog();  //打印ARouter日志
            ARouter.openDebug();  //开启ARouter的调试模式(如果在InstantRun模式下运行,必须开启调试模式,线上版本需要关闭，否则有安全风险),
        }
        //官方建议在Application里面进行初始化(使用该注解路径至少两级)
        ARouter.init(this);

    }

    /**统一处理异常，如重新登录、强制下线、异常反馈、网络检查*/
    private fun dealGlobalException(ex: GlobalException) {
//        LogUtils.d("dealGlobalException", ex.code.toString())
        when (ex.code) {
            401 -> {
                LoginResultHelper.failed(this, true)
            }
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stop() {

    }
}